package utils

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
)

var SqlDb *sql.DB

func init() {

	sqlStr := "root:root@tcp(localhost:3306)/e_order_trace?charset=utf8&parseTime=true&loc=Local"
	var err error
	SqlDb, err = sql.Open("mysql", sqlStr)
	if err != nil {
		fmt.Println("数据库打开出现了问题", err)
		return
	}
	err = SqlDb.Ping()
	if err != nil {
		fmt.Println("数据库连接出现了问题", err)
		return
	}

}

func DoQuery(db *sql.DB, sqlInfo string, args ...interface{}) ([]map[string]interface{}, interface{}, error) {
	rows, err := db.Query(sqlInfo, args...)
	if err != nil {
		return nil, nil, err
	}
	columns, _ := rows.Columns()
	columnLength := len(columns)
	//临时存储每行数据
	cache := make([]interface{}, columnLength)
	//为每一列初始化一个指针
	for index, _ := range cache {
		var a interface{}
		cache[index] = &a
	}
	//返回的切片
	var list []map[string]interface{}
	for rows.Next() {
		_ = rows.Scan(cache...)
		item := make(map[string]interface{})
		for i, data := range cache {
			item[Case2Camel(columns[i])] = *data.(*interface{})
		}
		list = append(list, item)
	}
	_ = rows.Close()
	if len(list) == 0 {
		return nil, nil, nil
	}
	if len(list) == 1 {
		return nil, list[0], nil
	}
	return list, nil, nil
}